﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace 文件管理
{



    class UdpManager
    {
        private UdpClient udpClient;
        private IPEndPoint groupEP;
        private UdpListener mUdpListener;
        bool isListening = false;

        public UdpManager()
        {
            int port = 9898;
            udpClient = new UdpClient(port);
            groupEP = new IPEndPoint(IPAddress.Any, port);
        }

        public void StartListening()
        {

            Thread readThread = new Thread(new ThreadStart(listening));
            readThread.Start();

        }

        public void listening()
        {
            try
            {
                Console.WriteLine("Waiting for incoming UDP datagrams...");
                isListening = true;
                while (isListening)
                {
                    byte[] bytes = udpClient.Receive(ref groupEP);

                    string receivedData = Encoding.ASCII.GetString(bytes, 0, bytes.Length);

                    //Console.WriteLine($"Received: {receivedData} from {groupEP}");

                    if (receivedData.StartsWith("rfid-"))
                    {
                        String name = receivedData.Split('-')[1];
                        string remoteIPAddress = groupEP.Address.ToString();
                        int remotePort = groupEP.Port;
                        if (mUdpListener != null)
                        {
                            mUdpListener.onReceived(name, remoteIPAddress);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                Console.WriteLine("udp read thread close");
                
            }

        }

        public void StopListenning()
        {
            isListening = false;
            mUdpListener = null;
            udpClient.Close();
        }

        public void setListener(UdpListener l)
        {
            mUdpListener = l;
        }
     

        static void Main1()
        {

            SocketClient client1 = new SocketClient();
            client1.connect("192.168.2.13");
            client1.send("hello");
            int port = 9898; // 您可以选择任何未被占用的端口
            UdpManager client = new UdpManager();
            Console.WriteLine("Main");
            UpdListenerImpl l = new UpdListenerImpl();
            client.setListener(l);
            // 在单独的线程中启动监听，以便主线程可以继续执行其他操作（如果需要）
            // 注意：在这个简单示例中，我们并没有创建新线程，因为主线程就是用来监听的。
            // 在实际应用中，您可能希望将监听逻辑放入后台线程或服务中。
            client.StartListening();

            Console.WriteLine("over");

        }
    }
    
    class UpdListenerImpl : UdpListener
    {

        public List<Device> devices = new List<Device>();

        public void onReceived(String name, String ip)
        {
            bool has = false;
            for (int i = 0;i < devices.Count(); i++)
            {
                if (devices[i].name.Equals(name))
                {
                    has = true;
                    break;
                }
            }
            //Console.WriteLine(name + ": " + ip);
            if (!has)
            {
                Console.WriteLine("has");
                devices.Add(new Device(name,ip));
                notifyDataChange(devices);
            }
        }

        protected virtual void notifyDataChange(List<Device> devices)
        {
            Console.WriteLine("father notifyDataChange");
        }
    }

    class Device
    {
       public string name;
       public string ip;

        public Device(string name, string ip)
        {
            this.name = name;
            this.ip = ip;
        }
    }

    public interface UdpListener
    {
        void onReceived(String name, String ip);
    }

}
